package terminal

import (
	"bufio"
	"os"
	"time"

	"device-admin/config/mysql"
	"device-admin/internal/app/grpc/protoc/robotc"
	"device-admin/internal/app/grpc/service/pubsub"
	"device-admin/internal/models"

	"192.168.1.75/go-pkg/helper"
	"google.golang.org/protobuf/proto"
)

// UpdateUpgradeStatus 更新升级状态
func UpdateUpgradeStatus(robotID, terminalType string, status int) {
	db := mysql.NewDB()
	// 更新终端状态
	db.Model(&models.Terminal{}).
		Where("robot_id = ?", robotID).
		Where("terminal_type = ?", terminalType).
		Updates(map[string]interface{}{
			"upgrade_status": status,
		})

	// 更新升级计划中的终端状态升级状态
	var terminalIDs []string
	db.Model(&models.UpgradeTerminals{}).
		Where("robot_id = ?", robotID).
		Where("terminal_type = ?", terminalType).
		Where("upgrade_status <> ?", 7). // 排除已取消升级的
		Order("created_at desc").
		Pluck("id", &terminalIDs)

	db.Model(&models.UpgradeTerminals{}).
		Where("id IN ?", terminalIDs).
		Updates(map[string]interface{}{
			"upgrade_status": status,
			"updated_at":     time.Now().Unix(),
		})
}

// 更新升级进度 UpdateUpgradeProgress
func UpdateUpgradeProgress(robotID, terminalType string, progress int) {
	db := mysql.NewDB()
	// 更新终端状态
	db.Model(&models.Terminal{}).
		Where("robot_id = ?", robotID).
		Where("terminal_type = ?", terminalType).
		Updates(map[string]interface{}{
			"updated_at":                time.Now().Unix(),
			"upgrade_download_progress": progress,
		})

	// 更新升级计划中的终端状态升级状态
	upgradeTerminals := models.UpgradeTerminals{}
	db.Model(&models.UpgradeTerminals{}).
		Where("robot_id = ?", robotID).
		Where("terminal_type = ?", terminalType).
		Where("upgrade_status <> ?", 7). // 排除已取消升级的
		Order("created_at desc").
		Take(&upgradeTerminals)

	db.Model(&models.UpgradeTerminals{}).
		Where("id = ?", upgradeTerminals.ID).
		Updates(map[string]interface{}{
			"updated_at":                time.Now().Unix(),
			"upgrade_download_progress": progress,
		})
}

// GetUpgradeContent 获取升级文件
func GetUpgradeContent(filename string, offset, length int64) (content []byte, totalSize int64, err error) {
	// 判断升级文件是否存在
	fs, err := os.Stat(filename)
	if err != nil {
		return nil, 0, err
	}

	fi, err := os.Open(filename)
	if err == nil {
		defer fi.Close()
	}
	if err != nil {
		return nil, 0, err
	}
	totalSize = fs.Size()
	r := bufio.NewReader(fi)
	buf := make([]byte, length)
	fi.Seek(offset, 0)
	n, err := r.Read(buf)
	if err != nil {
		return nil, totalSize, err
	} else {
		return buf[:n], totalSize, nil
	}
}

// SendUpgradeContent 发送升级内容
func SendUpgradeContent(robotID, terminalType string, content []byte, seq string, err error) error {
	rspTransmissionFile := &robotc.RspTransmissionFile{}
	if err != nil {
		rspTransmissionFile.Status = -1
	}
	rspTransmissionFile.Content = content
	rspTransmissionFile.Md5 = helper.Md5Bytes(content)
	msgFullName := string(rspTransmissionFile.ProtoReflect().Descriptor().FullName())
	bytes, _ := proto.Marshal(rspTransmissionFile)
	if terminalType == "95" {
		pubsub.LocalMsgPublish(robotID, terminalType, "wildmsg", msgFullName, bytes, seq)
	} else {
		pubsub.LocalMsgPublish(robotID, terminalType, "msg", msgFullName, bytes, seq)
	}
	return nil
}

// UpdateTerminalUpgradeResult 更新终端的升级结果
func UpdateTerminalUpgradeResult(robotID, terminalType, currentVersion string) {
	db := mysql.NewDB()
	var upgradeTerminal models.UpgradeTerminals
	rowsAffected := db.Model(&models.UpgradeTerminals{}).
		Where("robot_id = ?", robotID).
		Where("terminal_type = ?", terminalType).
		Where("upgrade_status <> ?", 7). // 排除已取消升级的
		Order("created_at desc").
		Take(&upgradeTerminal).RowsAffected
	// 如果升级进度为100%，且上报版本与目标版本一直，则直接更新为升级成功
	if rowsAffected > 0 {
		rowsAffected := db.Model(&models.UpgradeTerminals{}).
			Where("id = ?", upgradeTerminal.ID).
			Where("upgrade_download_progress = 100").
			Where("upgrade_version = ?", currentVersion).
			Updates(map[string]interface{}{
				"upgrade_status": 5,
			}).RowsAffected

		if rowsAffected > 0 {
			db.Model(&models.Terminal{}).
				Where("robot_id = ?", robotID).
				Where("terminal_type = ?", terminalType).
				Updates(map[string]interface{}{
					"upgrade_status": 5,
				})
		}
	}
}
